package com.diamond.web.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {
	public static List<String[]> readExcel(String filePath) throws IOException {
		return readExcel(new FileInputStream(filePath));
	}

	public static List<String[]> readExcel(InputStream stream) throws IOException {
		XSSFWorkbook workbook = new XSSFWorkbook(stream);
		XSSFSheet sheet0 = workbook.getSheetAt(0);
		List<String[]> rowList = new ArrayList<String[]>();
		for (int i = 0; i < sheet0.getLastRowNum(); i++) {
			XSSFRow r = sheet0.getRow(i);
			String[] data = new String[r.getLastCellNum()];
			for (int n = 0; n < data.length; n++) {
				XSSFCell cell = r.getCell(n);
				String str = getValue(cell);
				data[n]=str;
			}
			rowList.add(data);
		}
		return rowList;
	}

	public static  String getValue(XSSFCell cell) {
		if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
			return String.valueOf(cell.getNumericCellValue());
		} else {
			return String.valueOf(cell.getStringCellValue());
		}
	}
	
	public static void main(String[] args) throws IOException {
		List<String[]> arr = readExcel("D:\\work\\Chintec\\yld\\售后配件价格.xlsx");
		for (String[] objects : arr) {
			System.out.println(Arrays.toString(objects));
		}
	}

	public static void exportExcel(List<Object[]> rowDatas, String[] titles,OutputStream out) throws IOException {
		XSSFWorkbook wb = new XSSFWorkbook();
		XSSFSheet sheet = wb.createSheet("sheet1");  
		XSSFRow head= sheet.createRow(0);
		for(int i=0;i<titles.length;i++){
			XSSFCell cell = head.createCell(i,XSSFCell.CELL_TYPE_STRING);
			String titleName = titles[i];
			cell.setCellValue(titleName);
		}
		for(int i=0;i<rowDatas.size();i++){
			XSSFRow row = sheet.createRow(1+i);
			Object[] datas = rowDatas.get(i);
			for(int n=0;n<datas.length;n++){
				String data = String.valueOf(datas[n]);
				XSSFCell cell = row.createCell(n,XSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(data);
			}
		}
		wb.write(out);
	}
}
